﻿// alcune funzioni di utilità
MapControl2.AAAUtils = function(){};
MapControl2.AAAUtils.prototype = {};

MapControl2.AAAUtils.fromEventToDivPixel = function(e, mapId, up){
    var relPos = MapControl2.AAAUtils.mousePosition(e), oEl = null;
    if (MapControl2.NAVIGATOR_IS_IE){ 
        oEl = e.srcElement.parentNode;
        if (up)
            oEl = oEl.parentNode.parentNode;   
    }else    
        oEl = e.currentTarget;
    
    var parentPos = MapControl2.AAAUtils.elementPosition(oEl, true, mapId);
    return new GPoint(relPos.x - parentPos.x, relPos.y - parentPos.y);
};

/*
Funzioni che danno la posizione del mouse relativa al div della mappa

uso:
    var relPos = MapControl2.AAAUtils.mousePosition(e);
    var parentPos = MapControl2.AAAUtils.elementPosition(e.currentTarget);
    ...style.left = (relPos.x - parentPos.x ) + "px";
    ...style.top = (relPos.y - parentPos.y ) + "px";
*/

MapControl2.AAAUtils.mousePosition = function(e) {
	e = !e ? window.event : e;
	if (e.pageX || e.pageY) {
		return {x:e.pageX, y:e.pageY};
	} else {
		x = e.clientX + document.body.scrollLeft - document.body.clientLeft;
		y = e.clientY + document.body.scrollTop - document.body.clientTop;
		return {x:x, y:y};
	}
};

// 
MapControl2.AAAUtils.elementPosition = function(obj, checkId, mapId) {
	var left = 0;
	var top = 0;
	var firstOffset = false;
	
	while(obj.offsetParent != null && obj.offsetParent && obj.offsetParent != "undefined") 
	{
	    if (checkId && obj.parentNode.parentNode.id == mapId && MapControl2.NAVIGATOR_IS_IE)
	        obj = obj.offsetParent;
	    else{
            left += obj.offsetLeft;
            top += obj.offsetTop;
            try{
                if(obj.offsetParent.scrollLeft)	
                    left-= obj.offsetParent.scrollLeft;
                if(obj.offsetParent.scrollTop)
                    top-= obj.offsetParent.scrollTop;
            }catch(a){}
            obj = obj.offsetParent;
        }
	}

	return {x:left, y:top};
};

MapControl2.AAAUtils.fromEventToAbsPixel = function(e, map){
    var normalProj = G_NORMAL_MAP.getProjection();
    var pixel = MapControl2.AAAUtils.fromEventToDivPixel(e, map.getContainer().id);
    
    // computing latlng..
    var absCenter = normalProj.fromLatLngToPixel(map.getCenter(), map.getZoom());
    var absPixel = new Object();
    absPixel.x = absCenter.x - (map._divCenter.x - pixel.x);
    absPixel.y = absCenter.y - (map._divCenter.y - pixel.y);
    return absPixel;
};

MapControl2.AAAUtils.addDomListener = function(source, event, handler){
    var ok = true;
    if (source.attachEvent)
        source.attachEvent(event, handler);
    else if (source.addEventListener)
        source.addEventListener(event, handler, true);
    else
        eval('source.' + event + ' = handler');
    return true
};

// converte un GeoLoc o GeoPoint in GLatLng
MapControl2.AAAUtils.toGLatLng = function(point)
{
    var lat = (point.lat? point.lat : point.Lat);
    var lng = (point.lng? point.lng : point.Lng);
    return (new GLatLng(parseFloat(lat), parseFloat(lng)));
};

// crea un AAAMarker a partire da un GeoLoc
MapControl2.AAAUtils.createMarkerFromPoint = function(point, marker_type, isLocked)
{
    var marker_description = point.address + "<br/>" + point.description;
    var marker = MapControl2.AAAMarker.createMarker(point, isLocked, marker_type, marker_description);
    return marker; 
};

MapControl2.AAAUtils.createGeoLocFromLatLng = function(latlng)
{
    var gloc = new Object();
    gloc.lat = latlng.lat();
    gloc.lng = latlng.lng();
    gloc.address = '...';
    gloc.description = '';
    gloc.gettingInUsers = [];
    gloc.gettingOffUsers = [];
    return gloc;
};

/* Takes a location expressed by latitude, longitude and address 
   and return a GeoLoc javascript representation*/
MapControl2.AAAUtils.createGeoLocFromGeoCodingQuery = function(lat, lng, addr)
{
    var gloc = new Object();
    gloc.Lat = lat;
    gloc.Lng = lng;
    gloc.Address = addr;
    gloc.Description = '';
    gloc.GettingInUsers = [];
    gloc.GettingOffUsers = [];
    return gloc;
};

MapControl2.AAAUtils.add_to_front = function(el, array)
{
    var a = new Array(el);
    for (var i = 0; i<array.length; i++)
    {
        a.push(array[i]);
    }
    return a;
};

MapControl2.AAAUtils.tileEncoding = function(tx, ty, zl)
{
    var quad;
	quad = "";
	for (var i = zl; i > 0; i--)
	{
		var mask = 1 << (i - 1);
		var cell = 0;
		if ((tx & mask) != 0)
			cell++;
		if ((ty & mask) != 0)
			cell += 2;
		quad += cell;
	}
	return quad;
};

var _googleEncPol = null;
function _initializeGPolylineDescriptorField(polyline)
{
    for(var key in polyline)
    {
        if(polyline[key] != null)
            if (polyline[key].points != null && polyline[key].levels != null)
            {
                _googleEncPol = key;
                break;
            }
    }    
};

var MAX_DUMP_DEPTH = 10; 

function dumpObj(obj, name, indent, depth) {

    if (depth > MAX_DUMP_DEPTH) {
         return indent + name + ": <Maximum Depth Reached>\n";
    }

    if (typeof obj == "object") {
         var child = null;
         var output = indent + name + "\n";
         indent += "\t";
         for (var item in obj)
         {
               try {
                      child = obj[item];
               } catch (e) {
                      child = "<Unable to Evaluate>";
               }
               if (typeof child == "object") {
                      output += dumpObj(child, item, indent, depth + 1);
               } else {
                      output += indent + item + ": " + child + "\n";
               }
         }
         return output;
    } else {
         return obj;
    }
};

// -------------------- polyline encoding --------------------------------------------------------
function encodeSignedNumber(num) {
  var sgn_num = num << 1;

  if (num < 0) {
    sgn_num = ~(sgn_num);
  }

  return(encodeNumber(sgn_num));
};

// Encode an unsigned number in the encode format.
function encodeNumber(num) {
  var encodeString = "";

  while (num >= 0x20) {
    encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
    num >>= 5;
  }

  encodeString += (String.fromCharCode(num + 63));
  return encodeString;
};

// Create the encoded bounds.
// This function will be used only to encode polyline rappresenting trip with
// non road vehichle, so polyline with few vertex. Therefore we ignore the optimization
// made by google Polyline wivh allow see less vertex in relation to zoom level.
function createEncodings(points) {
  var i = 0;
  var plat = 0;
  var plng = 0;
  var encoded = new Object();
  encoded.points = "";
  encoded.numLevels = 1;
  encoded.zoomFactor = 0;
  encoded.levels = "";  
  
  for(i = 0; i < points.length; ++i) {
    var point = points[i];
    var lat = point.lat();
    var lng = point.lng();

    var late5 = Math.floor(lat * 1e5);
    var lnge5 = Math.floor(lng * 1e5);

    dlat = late5 - plat;
    dlng = lnge5 - plng;

    plat = late5;
    plng = lnge5;

    encoded.points += encodeSignedNumber(dlat) + encodeSignedNumber(dlng);
    
    encoded.levels += "B";
  } 
  return encoded;
};

MapControl2.AAAUtils.encodeGPolyline = function(poly){
    
    var latlngs = new Array(), prevVertex = null, currVertex = null, saved=0;
    for (var i=0; i<poly.getVertexCount(); i++){
        currVertex = poly.getVertex(i);
        if (!currVertex.equals(currVertex)){
            latlngs.push(currVertex);
            prevVertex = currVertex;
        }else
            saved++;
    }
    return (createEncodings(latlngs));
};
// -----------------------------------------------------------------------------------------------

function getIstructions (divToWrite,trip,callback)
{
     var tripMod= trip.getTripModel ();
     var str="";
     var routeArr=tripMod.routes;
     var listPoint=new Array ();
     for (var i=0;i<routeArr.length;i++)
     {
        var llp=new google.maps.LatLng (routeArr[i].start.lat,routeArr[i].start.lng);
        listPoint.push(llp);
        var wayPoint =routeArr[i].viaPoints;
        for (var k=0;k<wayPoint.length;k++)
        {
            var vp=new google.maps.LatLng (wayPoint[k].lat,wayPoint[k].lng);
            listPoint.push(vp);
        }
     }
     var ep=new google.maps.LatLng (routeArr[routeArr.length-1].end.lat,routeArr[routeArr.length-1].end.lng);
     listPoint.push(ep);
     var dirIstr = new google.maps.Directions();
     google.maps.Event.bind(dirIstr , "load", dirIstr, 
            function () 
            {
                for (var j=0;j<dirIstr.getNumRoutes();j++)
                {
                    var route=dirIstr.getRoute(j);
                    for (var k=0;k<route.getNumSteps();k++)
                    {
                        var step=route.getStep (k);
                        str=str+"<br>"+step.getDescriptionHtml();
                       var dv=document.getElementById (divToWrite);
                        dv.innerHTML= str;
                    }
                }
            }  
      );
	 google.maps.Event.bind(dirIstr, "error", dirIstr, function () {alert ("errore load istruzioni guida");});		
	 dirIstr.loadFromWaypoints(listPoint,{getSteps:true,locale:mapStrings["language_istructions"]});
};


function SetHelp (map,textHelp)
{
    function HelpControl() {}
    
    HelpControl.prototype = new google.maps.Control();

    HelpControl.prototype.initialize = function (map)
        {
          var buttonHelp = document.createElement("div");
          buttonHelp.id="buttonH";
          buttonHelp.style.color = "#0000cc";
          buttonHelp.style.backgroundColor = "white";
          buttonHelp.style.font = "small Arial"; 
          buttonHelp.style.border = "1px solid black";
          buttonHelp.style.padding = "2px";
          buttonHelp.style.marginBottom = "3px";
          buttonHelp.style.textAlign = "center";
          buttonHelp.style.width = "auto";
          buttonHelp.style.cursor = "pointer";
          buttonHelp.appendChild(document.createTextNode("Help"));
         google.maps.Event.addDomListener(buttonHelp, "click", function() 
         {
               var cont=document.getElementById ("buttonH");
               if (cont.childNodes.length==1)
               {
                   var helpDiv = document.createElement("div"); 
                   
                   helpDiv.id = "helpT";
                   helpDiv.style.backgroundColor = "white";
                   helpDiv.style.color = "#111111";
                   helpDiv.style.width = "auto";
                   helpDiv.style.border = "1px solid black";
                   helpDiv.style.padding = "2px";
                   helpDiv.style.position = "relative";
                   
                   helpDiv.innerHTML = textHelp;
                   cont.innerHTML ="X";
                   cont.appendChild(helpDiv);
               
                   google.maps.Event.addDomListener(helpDiv, "click", function() {
                        var cont2=document.getElementById ("buttonH");
                        var hel=document.getElementById ("helpT");
                        cont2.removeChild (hel);
                        cont2.innerHTML ="Help";
                   });
              }
              else   
              {
                  var hel=document.getElementById ("helpT");
                  cont.removeChild (hel);
                  cont.innerHTML ="Help";
              }    
             
          });

         map.getContainer().appendChild(buttonHelp);
                     
         return buttonHelp;
        }
        
      HelpControl.prototype.getDefaultPosition = function() {
         return new google.maps.ControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 7));
        }  
        
     map.addControl(new HelpControl());   
};

// -------------------------------------------------------------------------------------------------

MapControl2.AAAUtils.registerClass('MapControl2.AAAUtils');

if (typeof(Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
